package com.zhangjg.database.common;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

public class Tool {

	public static boolean isEmpty(String str) {
		return (str == null || str.length() == 0);
	}

	public static boolean isBlank(String str) {
		return (str == null || str.trim().length() == 0);
	}
	
	public static String lowerFirstChar(String str){
		if(str == null){
			return null;
		}
		if(str.length() > 0){
			return str.substring(0, 1).toLowerCase() + (str.length() > 1 ? str.substring(1) : "");
		}else{
			return "";
		}
	}

	public static String stringValue(String v, String def) {
		if (v == null || v.length() == 0)
			return def;
		return v.trim();
	}


	public static byte byteValue(String v, byte def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return Byte.parseByte(v);
		} catch (Exception e) {
			return def;
		}
	}

	public static char charValue(String v, char def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return (char) Integer.parseInt(v);
		} catch (Exception e) {
			return def;
		}
	}

	public static int intValue(String v, int def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return Integer.parseInt(v.trim());
		} catch (Exception e) {
			return def;
		}
	}

	public static Integer integerValue(String v) {
		return integerValue(v, null);
	}
	
	public static Integer integerValue(String v, int def) {
		if (isEmpty(v))
			return new Integer(def);
		try {
			return Integer.valueOf(v);
		} catch (Exception e) {
			return new Integer(def);
		}
	}
	public static Integer integerValue(String v, Integer def) {
		if (isEmpty(v))
			return def;
		try {
			return Integer.valueOf(v);
		} catch (Exception e) {
			return def;
		}
	}

	public static long longValue(String v, long def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return Long.parseLong(v.trim());
		} catch (Exception e) {
			return def;
		}
	}

	public static boolean booleanValue(String v, boolean def) {
		if (v == null || v.length() == 0)
			return def;

		if (v.equalsIgnoreCase("true") || v.equalsIgnoreCase("yes")
				|| v.equalsIgnoreCase("1")) {
			return true;
		} else if (v.equalsIgnoreCase("false") || v.equalsIgnoreCase("no")
				|| v.equalsIgnoreCase("0")) {
			return false;
		} else {
			return def;
		}
	}

	public static float floatValue(String v, float def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return Float.parseFloat(v.trim());
		} catch (Exception e) {
			return def;
		}
	}
	
	public static float floatValue(String v ,int remain, float def) {
		try {
			BigDecimal bd = new BigDecimal(v);
			bd = bd.setScale(remain,BigDecimal.ROUND_HALF_UP);
			return bd.floatValue();
		} catch (Exception e) {
			return def;
		}
	}

	public static double doubleValue(String v, double def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return Double.parseDouble(v.trim());
		} catch (Exception e) {
			return def;
		}
	}

	public static Date dateValue(String v, String fm, Date def) {
		if (v == null || v.length() == 0)
			return def;
		try {
			return new SimpleDateFormat(fm).parse(v.trim());
		} catch (Exception e) {
			return def;
		}
	}

	public static Date dateValue(String v, Date def) {
		return dateValue(v, "yyyy-MM-dd", def);
	}

	public static Date datetimeValue(String v, Date def) {
		return dateValue(v, "yyyy-MM-dd HH:mm:ss", def);
	}
	
	//�Զ��ж�ʱ���ʽ
	public static Date dateValueEx(String v, Date def, boolean timeStart) {
		if (v == null || v.length() == 0)return def;
		if(v.matches("\\d+-\\d+-\\d+ \\d+:\\d+")){
			if(timeStart){
				v += ":00";
			}else{
				v += ":59";
			}
			//System.out.println("-----2-"+v);
		}else if(v.matches("\\d+-\\d+-\\d+ \\d+")){
			if(timeStart){
				v += ":00:00";
			}else{
				v += ":59:59";
			}
		}else if(v.matches("\\d+-\\d+-\\d+")){
			if(timeStart){
				v += " 00:00:00";
			}else{
				v += " 23:59:59";
			}
		}
		return dateValue(v, "yyyy-MM-dd HH:mm:ss", def);
	}
	
	public static Date getToday() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static Date getTodayOffset(int offset) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, offset);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static Date getTheday(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTime();
	}
	
	public static Date getThedayLast(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		cal.set(Calendar.MILLISECOND, 999);
		return cal.getTime();
	}


	public static String format(Date date, String fmt) {
		DateFormat formatter = new SimpleDateFormat(fmt);
		return formatter.format(date);
	}

	public static String format(Date date) {
		return format(date, "yyyy-MM-dd");
	}
	
	public static String formatTime(Date date) {
		return format(date, "yyyy-MM-dd HH:mm:ss");
	}

	public static String format() {
		return format(new Date(System.currentTimeMillis()), "yyyy-MM-dd");
	}

	
	static public List<String> string2List(String str,String split){
		List<String> list = null;
		String temp[] = string2Array(str,split);
		if(temp == null)return list;
		list = Arrays.asList(temp);
		return list;
	}
	
	static public String[] string2Array(String str,String split){
		if(str == null || str.equals("")){
			return null;
		}
		String temp[] = str.split(split);
		if(split.equals("")){
			String result[] = new String[temp.length-1];
			for(int i=0;i<result.length;i++){
				result[i]=temp[i+1];
			}
			return result;
		}else{
			return temp;
		}
	}
	
	static public String array2String(String str[],String split){		
		if(str == null){
			return "";
		}
		String result = "";
		for(int i=0;i<str.length;i++){
			if(!result.equals("")){
				result += split;
			}
			result += str[i];
		}
				
		return result;
	}
	
	static public String list2String(List list,String split){		
		if(list == null){
			return "";
		}
		String result = "";
		for(int i=0;i<list.size();i++){
			if(!result.equals("")){
				result += split;
			}
			result += (String)list.get(i);
		}				
		return result;
	}
	
	
	public static String getLocalHostIp(){
		InetAddress addr = null;
		String address = "";
		try{
			addr = InetAddress.getLocalHost();
			address = addr.getHostAddress().toString();
			
			if(address.indexOf("127.0.0.1")!=-1){
				Enumeration netInterfaces=NetworkInterface.getNetworkInterfaces();
				InetAddress ip = null;
				while(netInterfaces.hasMoreElements()){
					NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement();
					System.out.println(ni.getName());
					ip=(InetAddress)ni.getInetAddresses().nextElement();
					if(!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":")==-1){
						address = ip.getHostAddress();
						break;
					}else{
						ip=null;
					}
				}
			}
		}catch(UnknownHostException uhe){
		}catch(SocketException se){
		}
		return address;//��ñ���IP
	}
	
	public static float floatDivide(int a,int b){
		if(b == 0){
			return 0.0f;
		}
		float f = (float)a/(float)b;
		f = Math.round(f*10)/10f;
		return f;
	}
	
	public static String cutString(String value,int length,String suffix){
		String strValue = value;
		int lengthByte = length * 2;
		boolean cut = false;
		if(strValue == null || strValue.equals("")){
			return "";
		}
		if (strValue.length() < length){
			strValue = toHTML(strValue,"<br>");
        	return strValue;
        }
		 if (strValue.length() > lengthByte){
             strValue = strValue.substring(0, lengthByte);
             cut = true;
         }
		 try{
	         byte[] bytes = strValue.getBytes("GBK");
	         if (bytes.length <= lengthByte) {
	         } else {
	         	cut = true;
	             byte[] newBytes = new byte[lengthByte];
	             System.arraycopy(bytes, 0, newBytes, 0, lengthByte);
	             strValue = new String(newBytes, "GBK");              
	             if (strValue.charAt(strValue.length() - 1) == (char) 65533) {
	                 strValue = strValue.substring(0, strValue.length() - 1);
	             }            
	         }
		 }catch(Exception e){
			 return "";
		 }
         strValue = toHTML(strValue,"<br>");
         if(!cut)suffix="";
         return strValue+suffix;
	}
	public static String toHTML(String str, String enter) {
        if(str == null || str.equals(""))return "";
        str = Tool.replace(str, "&", "&amp;");
        str = Tool.replace(str, "<", "&lt;");
        str = Tool.replace(str, ">", "&gt;");
        str = Tool.replace(str, " ", "&nbsp;");
        str = Tool.replace(str, "\r\n", "\n");
        str = Tool.replace(str, "\n", enter);
        str = Tool.replace(str, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        str = Tool.replace(str, "'", "&#039;");
        str = Tool.replace(str, "\"", "&#034;");
        return str;
    }
	// max �Ǹ����Ļ���ȫ���滻
	public static String replace(String text, String repl, String with, int max) {
		if (text == null || repl == null || with == null || repl.length() == 0
				|| max == 0) {
			return text;
		}
		StringBuffer buf = new StringBuffer(text.length());
		int start = 0, end = 0;
		while ((end = text.indexOf(repl, start)) != -1) {
			buf.append(text.substring(start, end)).append(with);
			start = end + repl.length();
			if (--max == 0) {
				break;
			}
		}
		buf.append(text.substring(start));
		return buf.toString();
	}

	// ȫ���滻
	public static String replace(String text, String repl, String with) {
		return replace(text, repl, with, -1);
	}
	
	public static void test(int a,int b){
		float f = (float)a/(float)b;
		System.out.println(f);
		f = Math.round(f*10)/10f;
		System.out.println(Math.round(f*10));
		System.out.println(f);
	}
	
	public static void main(String arg[]){
		//test(3,7);
		String s = "����³��Ե����á������Ÿ�Crosstour97";
		System.out.println(Tool.cutString(s, 13, ""));
	}
	
	
	
	
}
